package com.hsgene.gateway.support.filter;

import com.hsgene.common.ClientType;
import com.hsgene.common.util.jwt.IJWTInfo;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.gateway.support.ClientRequestFilter;
import com.hsgene.gateway.util.JwtToken;
import com.hsgene.user.exception.UserErrorCode;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 花生仁请求过滤器
 *
 * @author wangbing
 * @version 1.0, 2018/11/9
 */
@Component
public class PeanutClientRequestFilter implements ClientRequestFilter {

    private final static Logger LOGGER = LoggerFactory.getLogger(PeanutClientRequestFilter.class);

    @Resource
    private JwtToken jwtToken;

    @Override
    public ClientType filterType() {
        return ClientType.PEANUT;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter(HttpServletRequest request) {
        return true;
    }

    @Override
    public ApiResult run(HttpServletRequest request) {
        // 校验花生仁用户
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            authorization = request.getHeader("authorization");
        }
        if (StringUtils.isEmpty(authorization)) {
            return ApiResult.fail(UserErrorCode.USER_NOT_LOGIN);
        }
        // JWT解析
        IJWTInfo userInfo;
        try {
            userInfo = jwtToken.getInfoFromToken(authorization);
        } catch (ExpiredJwtException expired) {
            LOGGER.error("Authorization-Token过期：", expired);
            return ApiResult.fail(UserErrorCode.USER_TOKEN_EXPIRED);
        } catch (Exception e) {
            LOGGER.error("Authorization-Token解析异常：", e);
            e.printStackTrace();
            return ApiResult.fail(UserErrorCode.USER_NOT_LOGIN);
        }

        if (userInfo == null) {
            LOGGER.error("用户登录检测失败：获取用户信息为空");
            return ApiResult.fail(UserErrorCode.USER_NOT_LOGIN);
        }
        LOGGER.info("花生仁用户[{}:{}:{}]访问：{} {}", userInfo.getId(), userInfo.getName(), userInfo.getUniqueName(), request.getMethod(), request.getRequestURL());

        return ApiResult.succ();
    }
}
